﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AMS.Chess.CommonLayer
{
    public class StandardChessGame
    {
        // exposing this for now just to get it working
        // TODO: tunnel methods thru ChessGame
        private PlayClock _clock;
        public PlayClock Clock
        {
            get { return _clock; }
        }

        // for now, making this concrete and public just to get it working
        // exposing this for now just to get it working
        // TODO: tunnel methods thru ChessGame
        private StandardChessBoard _board;
        public StandardChessBoard ChessBoard
        {
            get { return _board; }
        }

        #region Observer Pattern code
        #region TimeExpired
        protected List<TimeExpiredDelegate> _observers;

        public delegate void TimeExpiredDelegate(ChessColor activePlayer);

        public void SubscribeTimeExpired(TimeExpiredDelegate delegateMethod)
        {
            // one subscription per person
            if (_observers.Contains(delegateMethod))
                return;

            _observers.Add(delegateMethod);
        }

        public void UnsubscribeTimeExpired(TimeExpiredDelegate delegateMethod)
        {
            if (_observers.Contains(delegateMethod))
                _observers.Remove(delegateMethod);
        }

        public void NotifyExpiredTime(ChessColor playerColor)
        {
            // notify all observers that time has expired
            foreach (TimeExpiredDelegate teDelegate in _observers)
                teDelegate(playerColor);
        }
        #endregion

        //
        #endregion

        public StandardChessGame()
        {
            _observers = new List<TimeExpiredDelegate>();
            _clock = PlayClock.GetSingletonInstance();
            Console.WriteLine("StandardChessGame is subscribing to PlayClock's Expiration notifier.");
            _clock.SubscribeTimeExpired(new PlayClock.TimeExpiredDelegate(ActOnTimeExpired));
            _board = new StandardChessBoard(new StandardChessPieceFactory());
        }

        private void ActOnTimeExpired(ChessColor playerColor)
        {
            Console.WriteLine("StandardChessGame was notified of PlayClock expiration.");
            NotifyExpiredTime(playerColor);
        }

        public void PlayGame()
        {
            // TODO: set everything up
            _clock.StartClock();

            // write game loop
            // implement as GameState observing for CurrentPlayer attempting action?

        }

        private void AttemptTurn(ChessColor playerColor)
        {
            // send up notification that player can act
            // wait for player to attempt to move piece
            
        }
    }
}
